/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkSipTcpClient.h"
#include "MkSipTcpListener.h"
#include "MkUtil/MkLog.h"

CMkSipTcpClient::CMkSipTcpClient(CMkEvent* pEvent, CMkTimer* pTimer, const MkEventRemovedCallback& RemovedCb, CMkSipTcpListener* pParent)
    : CMkTcpClient(pEvent, pTimer, RemovedCb)
    , m_pParent(pParent)
    , m_nMaxLen(Len20K)
    , m_nOffset(0)
{
    m_pRecvBuf = (Uint8*)malloc(m_nMaxLen);
}

Uint32 CMkSipTcpClient::OnRecv()
{
    Uint32 nToRead = m_nMaxLen - m_nOffset;
    if (0 == nToRead || !m_pParent) {
        MkErrorLog("recv max len not parse sip failed\n");
        Close();
        return NoneError;
    }
    Uint32 ErrorCode = Recv(m_pRecvBuf + m_nOffset, nToRead);
    MkCheckErrorLog(ErrorCode, "sip client recv failed\n");
    m_nOffset += nToRead;
    Uint32 nTotalUsed = 0;
    while (nTotalUsed < m_nOffset) {
        Uint32 nUsed = 0;
        ErrorCode = m_pParent->OnSipRecved(m_pRecvBuf + nTotalUsed, m_nOffset - nTotalUsed, GetRemoteHost(), GetRemotePort(), GetLocalHost(), GetLocalPort(), nUsed);
        if (SocketClosed == ErrorCode) {
            return NoneError;
        }
        if (NotHasEnoughBuffer == ErrorCode) {
            break;
        }
        if (NoneError != ErrorCode) {
            MkErrorLog("parse sip msg:%s error\n", m_pRecvBuf);
            Close();
            return NoneError;
        }
        nTotalUsed += nUsed;
    }
    m_nOffset -= nTotalUsed;
    memmove(m_pRecvBuf, m_pRecvBuf + nTotalUsed, m_nOffset);
    return NoneError;
}

CMkSipTcpClient::~CMkSipTcpClient()
{
    MkFree(m_pRecvBuf);
}